"""
Web related functionality
"""

import atlas
from atlas import hdf, sql
from itertools import ifilter

def label_cache( conf ):
    """
    Initializes the database handelers
    """
    session = sql.get_session(conf.SQL_URI)
    cache = {}
    # preload labels for faster filtering
    for lab in session.query(sql.Label):
        cache[ lab.name ] = lab.id
    return cache        

def close_connections():
    """
    Closes an open database handler
    """
    global hdf_db
    if hdf_db is not None:
        hdf_db.close()

def feature_query(session, param):
    """
    Returns all features on a given chromosome and within a start,end interval
    """
    feat = sql.Feature
    query = session.query(feat).filter( 
        "chrom=:chrom and ( (start>=:start and start<:end) or (end>=:start and end<:end) or (start<:start and end>:end) or (end<:start and start>:end))"
    ).params(start=param.start, end=param.end, chrom=param.chrom).order_by("start")
    return query

def feature_filter( data, name, strand=None, value=None, kdict={}):
    """
    Filter features
    """
    label_id = kdict.get(name)
    
    if label_id is None:
        atlas.warn( 'invalid feature name %s' % name)

    # chaining various filters
    results = ifilter( lambda x: x.label_id==label_id, data)

    if strand:
        results = ifilter( lambda x: x.strand==strand, results)
    
    if value is not None:
        results = ifilter( lambda x: x.value >= value,results)
    
    return list( results )

def feature2data( feats ):
    """
    Transforms features into a list of (start,end, name) tuples
    """
    return[ (r.start, r.end, str(r.name) ) for r in feats ]

def test( verbose=0 ):
    "Performs module level testing"
    import doctest
    doctest.testmod( optionflags=doctest.ELLIPSIS + doctest.NORMALIZE_WHITESPACE, verbose=verbose )

if __name__ == "__main__":
    test()
    from home import webconf as conf

    print label_cache( conf )
